package com.tajlip;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Abstracts the Java code required to pull data from Google's database and
 * send it to a browser as 'image/png'.
 */
public class ShowImageFilter implements Filter {

    private FilterConfig filterConfig = null;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // the comic to show (optional)
        Integer id = null;
        if (req.getRequestURI().contains("/images/")) {
            try {
                String url = req.getRequestURI();
                url = url.replace("-thumb", "");
                id = Integer.parseInt(url.split("/images/|\\.png")[1]);
            } catch (Exception e) {
                // noop
            }
        }

        // flag for if this is the small image
        boolean useSmall = req.getRequestURI().contains("-thumb");

        // open a reference to Google's database
        DatastoreService dataService = DatastoreServiceFactory.getDatastoreService();

        // query all the comies from BigTable
        Query query = new Query(Comic.KIND);
        query.addSort("timestamp", SortDirection.DESCENDING);
        if (id != null) {
            query.addFilter("id", Query.FilterOperator.EQUAL, id);
        }
        PreparedQuery preparedQuery = dataService.prepare(query);

        // get the result. there should always be exactly one
        Entity result = preparedQuery.asSingleEntity();

        // set the HTTP header to indicate this is a PNG -- not text/html
        res.setContentType("image/png");
        // write out the image as binary
        ServletOutputStream sos = res.getOutputStream();
        if (useSmall) {
            Blob blob = (Blob) result.getProperty("image-small");
            sos.write(blob.getBytes());
        }
        else {
            Blob blob = (Blob) result.getProperty("image");
            sos.write(blob.getBytes());
        }
        sos.flush();
    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
}